package cn.bone.gateway.web;


import cn.bone.common.http.CommonHeader;
import cn.bone.common.http.CommonRequest;
import cn.bone.common.http.CommonResult;
import cn.bone.common.http.ResultFactory;
import cn.bone.gateway.bean.ErrorRecord;
import cn.bone.gateway.dao.ErrorRecordDao;
import cn.bone.gateway.dao.JedisDao;
import cn.bone.gateway.service.ApiService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * Created by superbone on 2017/3/27.
 */
@RestController
public class ApiController {

    @Resource
    private ApiService apiService;
    @Resource
    private JedisDao jedisDao;
    @Resource
    private ErrorRecordDao recordDao;

    public DeferredResult<CommonResult<?>> api(
            HttpServletRequest request,HttpServletResponse response){

        String json = null;
        CommonHeader header = null;
        try (InputStream inputStream = request.getInputStream()){

            json = IOUtils.toString(inputStream,"UTF-8");
            JSONObject obj = JSON.parseObject(json);
            header = obj.getObject("header",CommonHeader.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(json==null||header==null){
            response.setStatus(400);
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            writer.print(ResultFactory.error("参数错误"));
            return null;
        }

        //设置超时时间,请求超过5秒直接返回超时提示
        final DeferredResult<CommonResult<?>> deferredResult =
                new DeferredResult<>(5000L,ResultFactory.timeOutError());
        ListenableFuture<CommonResult<?>> future =
                apiService.asyncExecute2(header,json);
        final CommonHeader finalHeader = header;
        future.addCallback(new ListenableFutureCallback<CommonResult<?>>(){

            @Override
            public void onSuccess(CommonResult<?> result) {

                deferredResult.setResult(result);
            }

            @Override
            public void onFailure(Throwable ex) {
                ErrorRecord record = new ErrorRecord();
                Integer errorId = jedisDao.getId("record");
                record.setErrorId(errorId);
                record.setHeader(finalHeader);
                record.setCreateTime(new Date());
                record.setExceptionClass(ex.getClass().getName());
                record.setExceptionMessage(ex.getMessage());
                StackTraceElement[] stackTrace = ex.getStackTrace();
                List<StackTraceElement> elementList = new ArrayList<>();
                for(StackTraceElement element : stackTrace){
                    elementList.add(element);
                }
                record.setLocalizedMessage(ex.getLocalizedMessage());
                record.setStackTraceElements(elementList);
                recordDao.save(record);
                deferredResult.setResult(ResultFactory.serverError(
                        "服务器错误,错误编号为<"+errorId+">"));
            }
        });
        return deferredResult;
    }

    /*@RequestMapping("/api")
    public DeferredResult<String> api(HttpServletRequest request) {

        String head = request.getHeader("Authorization");
        String host = request.getRemoteHost();
        String param = null;
        try {
           InputStream is = request.getInputStream();
           param = IOUtils.toString(is,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

        String timeOutResult = apiService.timeOutResult;

        //设置超时时间,请求超过5秒直接返回超时提示
        final DeferredResult<String> deferredResult =
                new DeferredResult<>(5000L,timeOutResult);

        ListenableFuture<String> future = apiService.asyncExecute(head,param,host);
        future.addCallback(new ListenableFutureCallback<String>(){

            @Override
            public void onSuccess(String result) {
                deferredResult.setResult(result);
            }

            @Override
            public void onFailure(Throwable ex) {

            }
        });

        return deferredResult;
    }*/

    @RequestMapping("/token")
    public String token(HttpServletRequest request, HttpServletResponse response){

        String head = request.getHeader("Authorization");
        String host = request.getRemoteHost();
        return apiService.token(head,host);
    }

    @RequestMapping("/upload")
    public String upload(HttpServletRequest request){

        return null;
    }

    /**
     * 添加api接口.内部开发使用
     * @param param
     * @return
     */
    @RequestMapping("/addMethod")
    public String addMethod(String param){

        return apiService.addMethod(param);
    }

}
